﻿using System;
using System.Collections.Generic;
using System.Linq;
using K9Tools.Abstractions.Dependency;
using K9Tools.Abstractions.Navigation;

namespace K9Tools.Core.Navigation;

public class DefaultNavigationManager : INavigationManager, ISingletonDependency
{
    private readonly List<NavigationViewItem> _menus = new(10);
    private bool _canNavigating;

    public IEnumerable<NavigationViewItem> Menus => _menus.OrderBy(a => a.Sort);

    public bool CanNavigating
    {
        get => _canNavigating;
        set
        {
            if (_canNavigating != value)
            {
                _canNavigating = value;
                CanNavigatingChanged?.Invoke(value);
            }
        }
    }

    public event Action<bool>? CanNavigatingChanged;

    public virtual INavigationManager Add(NavigationViewItem item)
    {
        if (item.Sort == 0) item.Sort = _menus.Count;
        _menus.Add(item);
        return this;
    }

    public virtual INavigationManager AddSubItem(string parentName, NavigationViewItem child)
    {
        var parent = _menus.FirstOrDefault(a => a.Name == parentName)
                     ?? throw new KeyNotFoundException("上级目录不存在: " + parentName);
        parent.AddSubItem(child);
        return this;
    }
}